from . import user_blueprint
from flask_login import login_required, current_user
from flask import render_template, request
from ..decorator import set_response_no_cache
from ..models.tables import User, Role
from .. import db
from ..config.config import CodeMap
from ..utils.common import set_response


@user_blueprint.route('/list')
@login_required
@set_response_no_cache
def user_list():
    all_user = User.query.all()
    return render_template('user/user_list.html', user_list=all_user)


@user_blueprint.route('/update')
@login_required
@set_response_no_cache
def user_update():
    return render_template('user/update_user.html')


@user_blueprint.route('/add')
@login_required
@set_response_no_cache
def user_add():
    roles = Role.query.all()
    status = [{
        'name': '正常',
        'value': 1
    }, {
        'name': '禁用',
        'value': 2
    }]
    return render_template('user/add_user.html', roles=roles, status=status)


@user_blueprint.route('/self')
@login_required
@set_response_no_cache
def self():
    user = User.query.get(current_user.id)
    print(list(user.role.menus))
    return render_template('user/self.html', user=current_user)


@user_blueprint.route('/info')
@login_required
@set_response_no_cache
def user_info():
    user = User.query.get(current_user.id)
    print(list(user.role.menus))
    return render_template('user/self.html', user=current_user)


@user_blueprint.route('/update.do', methods=['POST'])
@login_required
def do_update():
    user = User.query.get(current_user.id)
    try:
        if request.form['nickname']:
            user.nickname = request.form['nickname']
        if request.form['qq']:
            user.qq = request.form['qq']
        if request.form['phone']:
            user.phone = request.form['phone']
        if request.form['intro']:
            user.intro = request.form['intro']
        if request.form['avatar']:
            user.avatar = request.form['avatar']
        if request.form['email']:
            user.email = request.form['email']
        db.session.commit()
        return set_response(CodeMap.SUCCESS, CodeMap.SUCCESS_MSG, {'id': user.id})
    except Exception:
        return set_response(CodeMap.MYSQL_ERROR, CodeMap.MYSQL_ERROR_MSG, None)




